package net.koodar.suite.admin.module.system.department.service;

import net.koodar.suite.admin.module.system.department.model.entity.Department;
import net.koodar.suite.admin.module.system.department.model.params.DepartmentParam;
import net.koodar.suite.admin.module.system.department.model.vo.DepartmentVo;
import net.koodar.suite.admin.module.system.department.repository.DepartmentRepository;
import net.koodar.suite.common.core.exception.ServiceException;
import net.koodar.suite.common.util.BeanUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门 业务
 *
 * @author liyc
 */
@Service
public class DepartmentService {

	private final DepartmentRepository departmentRepository;

	public DepartmentService(DepartmentRepository departmentRepository) {
		this.departmentRepository = departmentRepository;
	}

	public List<Department> getAllList() {
		return departmentRepository.findAll();
	}

	public List<DepartmentVo> toTree(List<Department> departments, List<Department> allDepartments) {
		List<DepartmentVo> menuVos = new ArrayList<>();
		for (Department department : departments) {
			DepartmentVo deptVo = new DepartmentVo();
			BeanUtil.copy(department, deptVo);
			List<Department> childrenList = allDepartments.stream()
					.filter(p -> p.getParentId().equals(department.getId()))
					.collect(Collectors.toList());
			if (!departments.isEmpty()) {
				List<DepartmentVo> children = toTree(childrenList, allDepartments);
				deptVo.setChildren(children);
			}
			menuVos.add(deptVo);
		}
		return menuVos;
	}

	public void addDepartment(DepartmentParam departmentParam) {
		int count = departmentRepository.countByParentIdAndDeptName(departmentParam.getParentId(), departmentParam.getDeptName());
		if (count > 0) {
			throw new ServiceException(String.format("当前部门下已存在名称为[%s]的部门", departmentParam.getDeptName()));
		}
		Department department = new Department();
		BeanUtil.copy(departmentParam, department);
		departmentRepository.save(department);
	}

	public void updateDepartment(DepartmentParam departmentParam) {
		Department dbDepartment = departmentRepository.findFirstByParentIdAndDeptName(departmentParam.getParentId(), departmentParam.getDeptName());
		if (dbDepartment != null) {
			if (!dbDepartment.getId().equals(departmentParam.getId())) {
				throw new ServiceException(String.format("当前部门下已存在名称为[%s]的部门", departmentParam.getDeptName()));
			}
		}
		Department department = new Department();
		BeanUtil.copy(departmentParam, department);
		departmentRepository.save(department);
	}
	public void deleteDepartment(Long id) {
		departmentRepository.deleteById(id);
	}
}
